package com.musicstore.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.musicstore.biz.AlbumBiz;
import com.musicstore.biz.GenreBiz;
import com.musicstore.biz.UserBiz;
import com.musicstore.entity.GenreEntity;
import com.musicstore.entity.UserEntity;

@Controller
public class UserController {
	@Autowired
	private GenreBiz genreBiz;
	@Autowired
	private UserBiz userBiz;
	
	@RequestMapping("/register")//访问url路径名字
	public String register(Model model){
		List<GenreEntity> genrelist = genreBiz.getAll();
		model.addAttribute("genrelist",genrelist);
		return "register";//返回到指定jsp页面
	}
	@RequestMapping("/save")
	public String save(UserEntity user){
		System.out.println(user);
		userBiz.register(user);
		return "redirect:login";
	}
	//登录
	@RequestMapping("/login")
	public String login(Model model){
		List<GenreEntity> genrelist = genreBiz.getAll();
		model.addAttribute("genrelist",genrelist);
		return "login";
	}
	@RequestMapping("/dologin")
	public String dologin(Model model,String userName,String passWord,HttpSession session,String returnUrl){
		UserEntity user = userBiz.dologin(userName, passWord);
		System.out.println("dologin returnUrl="+returnUrl);
		if(user!=null){
			session.setAttribute("user", user);
			if(user!=null&&user.getUserRoleId()==1){
				if(returnUrl!=null&& !returnUrl.isEmpty()){
					return "redirect:"+returnUrl;
				}else{
					return "redirect:albumlist";
				}
			}
			return "redirect:albumlist";
		}
		model.addAttribute("error", "用户名或密码错误");
		return "login";
	}
	@RequestMapping("/loginAdmin")
	public String loginAdmin(){
		return "admin/admin_default";
	}
	
	public void check(String userName,HttpServletResponse  response) throws IOException{
		int count = userBiz.checkUserName(userName);
		PrintWriter out = response.getWriter();
		out.print(out);
	}
}
